<template>
  <div class="w-full h-full px-4">

    <el-form :inline="true" :model="data" class="w-full flex justify-between px-4 pt-4">
      <el-form-item class="label" :label="$t('iot.time')">
        <el-date-picker
          v-model="data.time"
          style="width: 240px"
          type="daterange"
          range-separator="-"
          :start-placeholder="$t('wms.startTime')"
          :end-placeholder="$t('wms.endTime')"
          class="custom-date-picker"
        />
      </el-form-item>
      <el-form-item class="label" :label="$t('tank.TankNumber')">
        <el-select v-model="data.TankNumber" style="width: 240px" clearable :placeholder="$t('wms.pleaseSelect')">
          <el-option
            v-for="item in data.optionList"
            :key="item.text"
            :label="item.text + ' - ' + item.Name_En"
            :value="item.text"

          />
        </el-select>
      </el-form-item>
      <el-form-item class="label" :label="$t('tank.MaterialNumber')">
        <el-select
          id="select"
          ref="selectTable"
          v-model="data.materialCode"
          @clear="clear"
          @click="onClick"
          style="width: 240px"
          clearable
          filterable
          :filter-method="filterMaterial"
        >
          <template #empty>
            <div style="padding: 0 10px;text-align: left" v-if="showList">
              <el-table
                ref="tableRef"
                border
                id="out-table"
                :data="materialList"
                :fit="true"
                table-layout="fixed"
                header-align="center"
                style="width:100%;height: 89%;"
                @row-click="rowClick"
                :header-cell-style="{
                color: '#1e293b',
                textAlign: 'center',
                fontWeight: '600',
                background: 'linear-gradient(to bottom, #f8fafc, #f1f5f9)',
                borderColor: '#e2e8f0',
                height: '10px'
              }"
                :cell-style="{
                textAlign: 'center',
                color: '#334155',
                borderColor: '#e2e8f0',
                background: '#fff',
                height: '10px'
              }"
              >
                <el-table-column prop="materialCode" :label="$t('wms.materialCode')" show-overflow-tooltip/>
                <el-table-column prop="materialName" :label="$t('wms.materialName')" show-overflow-tooltip/>
              </el-table>
              <div class="paging" v-if="data.curPage && data.pageSize && data.total2">
                <el-pagination
                  :page-size="data.pageSize || 10"
                  :pager-count="5"
                  small
                  :current-page="data.curPage"
                  :total="data.total2"
                  background
                  layout="total, sizes, prev, pager, next, jumper"
                  @size-change="sizeChange"
                  @current-change="currentChange"
                />
              </div>
            </div>
          </template>
        </el-select>
        <!--      <el-select  v-model="data.MaterialNumber" clearable style="width: 220px" :placeholder="$t('wms.pleaseSelect')">-->
        <!--        <el-option-->
        <!--          v-for="item in data.optionList2"-->
        <!--          :key="item.value"-->
        <!--          :label="item.value"-->
        <!--          :value="item.value"-->

        <!--        />-->

      </el-form-item>
      <el-button icon="Search" class="buttons" type="primary" @click="getSearch">{{ $t('wms.search') }}</el-button>
    </el-form>

    <el-tabs type="border-card" class="tab-card" v-model="queryForm.taskStatus" @tab-click="handleClick">
      <el-tab-pane v-for="item in options" :key="item.value" :label="item.label" :name="item.value">
        <template #label>
          <span :class="item.color"><i :class="['iconfont', item.icon, 'mr-2',item.color]"></i>{{ item.label }}</span>
        </template>
        <div class="table-list w-full h-full p-3">
          <el-table
            ref="tableRef"
            border
            id="out-table"
            :data="detailList"
            :fit="true"
            table-layout="fixed"
            header-align="center"
            v-loading="data.Loading"
            show-summary
            :summary-method="getSummaries"
            style="width:100%;height: 89%;"
            :header-cell-style="{
        color: '#1e293b',
        textAlign: 'center',
        fontWeight: '600',
        background: 'linear-gradient(to bottom, #f8fafc, #f1f5f9)',
        borderColor: '#e2e8f0',
        height: '40px'
      }"
            :cell-style="{
        textAlign: 'center',
        color: '#334155',
        borderColor: '#e2e8f0',
        background: '#fff',
        height: '40px'
      }"
          >
            <el-table-column prop="operate_desc" v-if="queryForm.taskStatus==t('tank.PremixedDetails')" :label="$t('mes.operateType')" width="150" show-overflow-tooltip>
              <template #default="scope">
                <el-tag type="info" style="width: 80px" effect="light">{{  scope.row.operate_desc }}</el-tag>
              </template>
            </el-table-column>

            <el-table-column prop="batch_no" v-if="queryForm.taskStatus==t('tank.PremixedDetails')" :label="$t('tank.pici')" width="150" show-overflow-tooltip>
              <template #default="scope">
                <el-tag :type="getBatchColor(scope.row.batch_no)" effect="light">{{  scope.row.batch_no }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="produce_end_time" :label="$t('tank.Date')" show-overflow-tooltip/>
            <el-table-column prop="material_code" :label="$t('tank.MaterialNumber')" show-overflow-tooltip>
              <template #default="scope">
                <el-tag type="warning" effect="light">{{ scope.row.material_code || '--' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="material_name" :label="$t('tank.MaterialName')" show-overflow-tooltip/>
            <el-table-column prop="specification" :label="$t('tank.MaterialSpecification')" show-overflow-tooltip/>
            <el-table-column v-if="queryForm.taskStatus==t('tank.PremixedDetails')" prop="source_location_code" :label="$t('tank.PutIntoTank')" align="center">
              <template #default="scope">
                <el-tag type="warning" effect="light">{{ scope.row.source_location_code || '--' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column v-if="queryForm.taskStatus==t('tank.InventoryDetails')" prop="location_code" :label="$t('tank.PutIntoTank')" align="center">
              <template #default="scope">
                <el-tag type="warning" effect="light">{{ scope.row.source_location_code || '--' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="qty" :label="$t('tank.InputWeight')" align="center">
              <template #default="scope">
                <el-tag type="success" effect="light">{{ scope.row.qty || '--' }} kg</el-tag>
              </template>
            </el-table-column>
          </el-table>

          <div class="flex justify-end mt-3">
            <el-pagination
              :current-page="data.page"
              :page-size="data.size"
              :page-sizes="[10, 20, 50, 100]"
              small
              background
              class="custom-pagination"
              layout="total, sizes, prev, pager, next, jumper"
              :total="data.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

  </div>
</template>

<script setup>
import { onMounted, reactive, ref, watch } from 'vue'
import '@/style/tailwind.css'

// 批次颜色映射逻辑
const batchColorMap = reactive(new Map())
const colorList = [
  'success', 'warning', 'info', 'danger', 'primary'
]
function getBatchColor(batchNo) {
  if (!batchNo) return ''
  if (!batchColorMap.has(batchNo)) {
    // 分配下一个颜色，循环使用
    const idx = batchColorMap.size % colorList.length
    batchColorMap.set(batchNo, colorList[idx])
  }
  return batchColorMap.get(batchNo)
}
import '@/assets/font/iconfont.css'
import { dicItemByCode } from '@/api/mesApi'
import useI18n from '@/hooks/language'
import moment from 'moment/moment'
import { onBeforeUnmount } from 'vue'
import { getTankNumDetailIn, getTankNumDetailOut, getTank, getMaterial } from '@/api/tankBodyApi'
import { debounce } from 'lodash-es'

const { t } = useI18n()

const queryForm = reactive({
  taskStatus: t('tank.InventoryDetails')
})
const detailList = ref([])
const materialList = ref([])
const sumQty = ref([])
const showList = ref(false)
const data = reactive({
  size: 20,
  page: 1,
  total: 0,
  total2: 0,
  curPage: 1,
  pageSize: 5,
  text: '',
  time: [],
  TankNumber: '',
  MaterialNumber: '',
  materialName:'',
  materialCode:'',
  optionList: [],
  optionList2: [],
  Loading: false,
  Loading2: false
})
const options = ref([
  {
    label: t('tank.InventoryDetails'),
    value: t('tank.InventoryDetails'),
    icon: 'icon-renwuguanliqi',
    color: 'text-blue-600'
  },
  {
    label: t('tank.PremixedDetails'),
    value: t('tank.PremixedDetails'),
    icon: 'icon-dengdai',
    color: 'text-yellow-600'
  }
])
// 点击tab切换
const handleClick = (tab) => {
  queryForm.taskStatus = tab.props.label
  //重置页码
  data.page = 1
  getDetailList()
}
const getSummaries = (param) => {
  const { columns } = param
if(queryForm.taskStatus==t('tank.InventoryDetails')) {
  return columns.map((column, index) => {
    if (index === 4) { // 假设数量列为索引 6
      return `sum`
    }

    if (index === 5) { // 假设数量列为索引 6
      return sumQty.value
    }
    return ''
  })
}else {
  return columns.map((column, index) => {
    if (index === 6) { // 假设数量列为索引 6
      return `sum`
    }

    if (index === 7) { // 假设数量列为索引 6
      return sumQty.value
    }
    return ''
  })
}

}
const getSearch = () => {
  data.page = 1
  getDetailList()
}
const handleSizeChange = (val) => {
  data.size = val
  getDetailList()
}
const handleCurrentChange = (val) => {
  data.page = val
  getDetailList()
}

const getList = async () => {
  const res = await getTank()
  data.optionList = res.data
}
const getMaterialList = async () => {
  const res = await getMaterial({
    key: data.text,
    size: data.pageSize,
    current: data.curPage
  })
  materialList.value = res.data.records
  data.total2 = res.data.total
}
const formatNumber = (num) => {
  if (Number.isInteger(Number(num))) {
    return num
  }
  return parseFloat(num).toFixed(2) || '--'
}
const getDefaultDateRange = () => {
  const today = moment()
  const startOfMonth = today.clone().startOf('month').format('YYYY-MM-DD')
  const endOfMonth = today.clone().endOf('month').format('YYYY-MM-DD')

  data.time = [startOfMonth, endOfMonth]
}
const getDetailList = async () => {
  data.Loading = true
  try {
    const params = {
      startTime: data?.time?.[0] ? moment(data.time[0]).format('YYYY-MM-DD') : '',
      endTime: data?.time?.[1] ? moment(data.time[1]).format('YYYY-MM-DD') : '',
      current: data.page,
      size: data.size,
      tankCode: data.TankNumber,
      materialCode: data.materialCode
    }
    let res = null
    if (queryForm.taskStatus == t('tank.PremixedDetails')) {
      res = await getTankNumDetailOut(params)
    } else if (queryForm.taskStatus == t('tank.InventoryDetails')) {
      res = await getTankNumDetailIn(params)
    }
    detailList.value = res.data.page.records?.map((item) => {
      return {
        ...item,
        qty: formatNumber(item.qty)
      }
    })
    data.total = res.data.page.total
    sumQty.value = formatNumber(res.data.sumQty)
    data.Loading = false
  } catch (e) {
    data.Loading = false
    console.log(e)
  }
}
const clear = () => {
  data.materialName = ''
  data.materialCode = ''
  data.text = ''
  data.curPage = 1
  getMaterialList()
}
// const onInput = (value) => {
//   console.log(value,'===')
//   // getMaterialList(val)
// }
// const handleSelectInput = () => {
//   console.log(222)
// }
const rowClick = (row) => {
 data.materialName = row.materialName
  data.materialCode = row.materialCode
  showList.value =false
}
const onClick = (val) => {
  showList.value = true
}
const sizeChange = (val) => {
  data.pageSize = val
  getMaterialList()
}
const currentChange = (val) => {
  data.curPage = val
  getMaterialList()
}
onMounted(async () => {
  await getList()
  await getMaterialList()
  getDefaultDateRange()
  getDetailList()
})
const filterMaterial = debounce(async (val) => {
  data.text = val
  data.curPage = 1
  await getMaterialList()
}, 300)
watch(() => data.time, () => {
  batchColorMap.clear()
})
onBeforeUnmount(() => {
  batchColorMap.clear()
})
</script>

<style scoped lang="scss">

</style>
